constructive algorithms dp implementation math trees *2400

Please click on ads to support us..

C++ Code:

# include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;
int n; 
vector <int> g[N];
int y, maxl;
int siz[N],dfn[N],dfntot = 0;
int L,R;
bool Ok = 1;
vector <int> S[N];
vector <int> Link;
int p[N];
void dfs(int x,int fa,int dep,bool xg = 0)
{
	if(dep > maxl) y = x, maxl = dep; 
	if(xg) siz[x] = 1,dfn[x] = ++dfntot;
	for(int i = 0; i < (int)g[x].size(); i++)
	{
		int v = g[x][i]; 
		if(v == fa) continue;
		dfs(v,x,dep + 1,xg);
		if(xg) siz[x] += siz[v];
	}
	return;
}
void dfs2(int x,int fa)
{
	if(!Ok) return;
	Link.push_back(x);
	for(int i = 0; i < (int)g[x].size(); i++)
	{
		int v = g[x][i]; if(v == fa) continue;
		if(dfn[v] <= dfn[R] && dfn[R] <= dfn[v] + siz[v] - 1) // R in T_v
		{
			dfs2(v,x);
		}
		else if(siz[v] > 1) 
		{
			Ok = 0; return;
		}
		else S[x].push_back(v);
	}
	return;
}
void solve(void)
{
	int tot = 0;
	int L = (int)Link.size();
	if(L % 2 == 0)
	{
		for(int i = 0; i < L; i += 2)
		{
			p[++tot] = Link[i];
//			if(i == L - 1) break;
			for(int v : S[Link[i + 1]]) p[++tot] = v;
		}
//		p[++tot] = L - 1;
//		for(int v : S[Link[L - 1]]) p[++tot] = v;
		for(int i = L - 1; i >= 0; i -= 2)
		{
			p[++tot] = Link[i];
			for(int v : S[Link[i - 1]]) p[++tot] = v;
		}
	}
	else 
	{
		for(int i = 0; i < L; i += 2)
		{
			p[++tot] = Link[i];
			if(i + 1 < L) 
			{
				for(int v : S[Link[i + 1]]) p[++tot] = v;
			}
		}
		for(int i = L - 2; i >= 0; i -= 2)
		{
			p[++tot] = Link[i];
			if(i - 1 >= 0)
			{
				for(int v : S[Link[i - 1]]) p[++tot] = v;
			}
		}
	}
	return;
}
int main(void)
{
	scanf("%d",&n);
	for(int i = 1; i < n; i++)
	{
		int u,v; scanf("%d%d",&u,&v);
		g[u].push_back(v),g[v].push_back(u);
	}
	y = 0, maxl = 0; 
	dfs(1,0,0); L = y,maxl = 0;
//	printf("y = %d, maxl = %d\n",y,maxl);
	dfs(L,0,0,1); R = y;
//	printf("L = %d,R = %d\n",L,R);
	dfs2(L,0);
//	printf("Link : \n");
//	for(int x : Link) printf("%d ",x);
//	printf("\n");
	if(!Ok) 
	{
		printf("No\n");
		return 0;
	}
	solve();
	printf("Yes\n");
	for(int i = 1; i <= n; i++) printf("%d ",p[i]);
	return 0;
}

   	  			  									 		 	 	 			


Comments

Submit
0 Comments
More Questions

1657C - Bracket Sequence Deletion
1657B - XY Sequence
1009A - Game Shopping
1657A - Integer Moves
230B - T-primes
630A - Again Twenty Five
1234D - Distinct Characters Queries
1183A - Nearest Interesting Number
1009E - Intercity Travelling
1637B - MEX and Array
224A - Parallelepiped
964A - Splits
1615A - Closing The Gap
4C - Registration System
1321A - Contest for Robots
1451A - Subtract or Divide
1B - Spreadsheet
1177A - Digits Sequence (Easy Edition)
1579A - Casimir's String Solitaire
287B - Pipeline
510A - Fox And Snake
1520B - Ordinary Numbers
1624A - Plus One on the Subset
350A - TL
1487A - Arena
1520D - Same Differences
376A - Lever
1305A - Kuroni and the Gifts
1609A - Divide and Multiply
149B - Martian Clock